package com.mall.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.common.result.Result;
import com.mall.system.entity.Role;
import com.mall.system.service.RoleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * 角色控制器
 */
@Tag(name = "角色管理")
@Slf4j
@RestController
@RequestMapping("/system/roles")
public class RoleController {
    
    @Autowired
    private RoleService roleService;
    
    @Operation(summary = "角色列表")
    @GetMapping
    public Result<IPage<Role>> list(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            Role role) {
        try {
            IPage<Role> page = new Page<>(pageNum, pageSize);
            QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
            
            // 添加查询条件
            if (role.getRoleName() != null && !role.getRoleName().isEmpty()) {
                queryWrapper.like("role_name", role.getRoleName());
            }
            if (role.getStatus() != null) {
                queryWrapper.eq("status", role.getStatus());
            }
            
            IPage<Role> result = roleService.page(page, queryWrapper);
            return Result.success(result);
        } catch (Exception e) {
            log.error("查询角色列表异常: ", e);
            return Result.failed(e.getMessage());
        }
    }
    
    @Operation(summary = "根据角色ID获取角色")
    @GetMapping("/{roleId}")
    public Result<Role> getById(@PathVariable("roleId") Long roleId) {
        try {
            Role role = roleService.getById(roleId);
            if (role != null) {
                return Result.success(role);
            } else {
                return Result.failed("角色不存在");
            }
        } catch (Exception e) {
            log.error("查询角色异常: ", e);
            return Result.failed(e.getMessage());
        }
    }
    
    @Operation(summary = "新增角色")
    @PostMapping
    public Result<Boolean> add(@RequestBody Role role) {
        try {
            boolean success = roleService.save(role);
            if (success) {
                return Result.success(true);
            } else {
                return Result.failed("新增角色失败");
            }
        } catch (Exception e) {
            log.error("新增角色异常: ", e);
            return Result.failed(e.getMessage());
        }
    }
    
    @Operation(summary = "更新角色")
    @PutMapping
    public Result<Boolean> update(@RequestBody Role role) {
        try {
            if (role.getRoleId() == null) {
                return Result.failed("角色ID不能为空");
            }
            
            boolean success = roleService.updateById(role);
            if (success) {
                return Result.success(true);
            } else {
                return Result.failed("更新角色失败");
            }
        } catch (Exception e) {
            log.error("更新角色异常: ", e);
            return Result.failed(e.getMessage());
        }
    }
    
    @Operation(summary = "删除角色")
    @DeleteMapping("/{ids}")
    public Result<Boolean> delete(@PathVariable("ids") List<Long> ids) {
        try {
            boolean success = roleService.removeByIds(ids);
            if (success) {
                return Result.success(true);
            } else {
                return Result.failed("删除角色失败");
            }
        } catch (Exception e) {
            log.error("删除角色异常: ", e);
            return Result.failed(e.getMessage());
        }
    }
    
    @Operation(summary = "获取所有角色列表")
    @GetMapping("/list")
    public Result<List<Role>> listAll() {
        try {
            QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", 1);
            queryWrapper.eq("del_flag", 0);
            queryWrapper.orderByAsc("role_sort");
            
            List<Role> roles = roleService.list(queryWrapper);
            return Result.success(roles);
        } catch (Exception e) {
            log.error("获取角色列表异常: ", e);
            return Result.failed(e.getMessage());
        }
    }
    
    @Operation(summary = "根据用户ID获取角色列表")
    @GetMapping("/user/{userId}")
    public Result<List<Role>> getRolesByUserId(@PathVariable Long userId) {
        try {
            List<Role> roles = roleService.selectRoleByUserId(userId);
            return Result.success(roles);
        } catch (Exception e) {
            log.error("根据用户ID获取角色列表异常: ", e);
            return Result.failed(e.getMessage());
        }
    }
    
    @Operation(summary = "根据用户ID获取角色权限字符串列表")
    @GetMapping("/user/{userId}/permissions")
    public Result<Set<String>> getRolePermissionsByUserId(@PathVariable Long userId) {
        try {
            Set<String> permissions = roleService.selectRolePermissionByUserId(userId);
            return Result.success(permissions);
        } catch (Exception e) {
            log.error("根据用户ID获取角色权限字符串列表异常: ", e);
            return Result.failed(e.getMessage());
        }
    }
}